package com.demo.download.server;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.ResponseExtractor;

import java.io.IOException;
import java.util.concurrent.CompletableFuture;
@Slf4j
public abstract class AbstractDisplayDownloadSpeedResponseExtractor<T> implements ResponseExtractor<T> ,DisplayDownloadSpeed{
    @Override
    public T extractData(ClientHttpResponse response) throws IOException {

        long contentLength = response.getHeaders().getContentLength();
        this.displaySpeed(Thread.currentThread().getName(),contentLength);
        return this.doExtractData(response);
    }

    protected abstract T doExtractData(ClientHttpResponse response) throws IOException;

    protected abstract long getAlreadyDownloadLength();

    @Override
    public void displaySpeed(String task, long contentLength) {
        long totalSize = contentLength / 1024;
        CompletableFuture.runAsync(() -> {
            long tmp = 0, speed;
            while(contentLength - tmp > 0){
                speed = getAlreadyDownloadLength() - tmp;
                tmp = getAlreadyDownloadLength();
                print(task,totalSize,tmp,speed);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    protected void print(String task,long totalSize,long tmp,long speed){
        log.info("{} 文件总大小  {} kb,已经下载 {} kb,下载速度{} kb/s",task,(tmp / 1024),(speed/1000));
    }
}
